import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'base_state.dart';
import 'list_state.dart';

/// 分页信息类
class PageInfo {
  final int page; // 当前页码
  final int pageSize; // 每页大小
  final int total; // 总数据量
  final bool hasMore; // 是否还有更多数据

  const PageInfo({
    this.page = 1,
    this.pageSize = 20,
    this.total = 0,
    this.hasMore = true,
  });

  /// 计算总页数
  int get totalPages => (total / pageSize).ceil();

  /// 是否是第一页
  bool get isFirstPage => page <= 1;

  /// 是否是最后一页
  bool get isLastPage => page >= totalPages || !hasMore;

  /// 获取下一页页码
  int get nextPage => page + 1;

  /// 复制并更新信息
  PageInfo copyWith({
    int? page,
    int? pageSize,
    int? total,
    bool? hasMore,
  }) {
    return PageInfo(
      page: page ?? this.page,
      pageSize: pageSize ?? this.pageSize,
      total: total ?? this.total,
      hasMore: hasMore ?? this.hasMore,
    );
  }

  @override
  String toString() {
    return 'PageInfo(page: $page, pageSize: $pageSize, total: $total, hasMore: $hasMore)';
  }
}

/// 刷新分页状态类
class RefreshState<T> extends ListState<T> {
  final PageInfo pageInfo;
  final bool isRefreshing; // 是否正在刷新

  const RefreshState({
    super.status,
    super.data,
    super.errorMessage,
    super.exception,
    super.hasMore,
    super.isLoadingMore,
    super.currentPage,
    super.totalCount,
    this.pageInfo = const PageInfo(),
    this.isRefreshing = false,
  });

  @override
  RefreshState<T> loading() {
    return RefreshState<T>(
      status: PageStatus.loading,
      data: data,
      hasMore: hasMore,
      isLoadingMore: isLoadingMore,
      currentPage: currentPage,
      totalCount: totalCount,
      pageInfo: pageInfo,
      isRefreshing: isRefreshing,
    );
  }

  @override
  RefreshState<T> success(List<T> newData) {
    return RefreshState<T>(
      status: PageStatus.success,
      data: newData,
      hasMore: pageInfo.hasMore,
      isLoadingMore: false,
      currentPage: pageInfo.page,
      totalCount: pageInfo.total,
      pageInfo: pageInfo,
      isRefreshing: false,
    );
  }

  @override
  RefreshState<T> empty() {
    return RefreshState<T>(
      status: PageStatus.empty,
      data: data,
      hasMore: false,
      isLoadingMore: false,
      currentPage: pageInfo.page,
      totalCount: 0,
      pageInfo: pageInfo.copyWith(hasMore: false, total: 0),
      isRefreshing: false,
    );
  }

  @override
  RefreshState<T> error(String message, [Exception? exception]) {
    return RefreshState<T>(
      status: PageStatus.error,
      data: data,
      errorMessage: message,
      exception: exception,
      hasMore: hasMore,
      isLoadingMore: false,
      currentPage: currentPage,
      totalCount: totalCount,
      pageInfo: pageInfo,
      isRefreshing: false,
    );
  }

  /// 设置刷新状态
  RefreshState<T> refreshing() {
    return RefreshState<T>(
      status: status,
      data: data,
      errorMessage: errorMessage,
      exception: exception,
      hasMore: hasMore,
      isLoadingMore: isLoadingMore,
      currentPage: currentPage,
      totalCount: totalCount,
      pageInfo: pageInfo,
      isRefreshing: true,
    );
  }

  /// 设置加载更多状态
  @override
  RefreshState<T> loadingMore() {
    return RefreshState<T>(
      status: status,
      data: data,
      errorMessage: errorMessage,
      exception: exception,
      hasMore: hasMore,
      isLoadingMore: true,
      currentPage: currentPage,
      totalCount: totalCount,
      pageInfo: pageInfo,
      isRefreshing: isRefreshing,
    );
  }

  /// 设置首次加载数据
  RefreshState<T> setInitialData(List<T> newData, PageInfo newPageInfo) {
    return RefreshState<T>(
      status: newData.isEmpty ? PageStatus.empty : PageStatus.success,
      data: newData,
      hasMore: newPageInfo.hasMore,
      isLoadingMore: false,
      currentPage: newPageInfo.page,
      totalCount: newPageInfo.total,
      pageInfo: newPageInfo,
      isRefreshing: false,
    );
  }

  /// 添加更多数据
  @override
  RefreshState<T> appendData(List<T> newData,
      {bool? hasMore, int? totalCount}) {
    final currentData = data ?? <T>[];
    final combinedData = [...currentData, ...newData];
    final newPageInfo = pageInfo.copyWith(
      page: pageInfo.nextPage,
      hasMore: hasMore ?? (newData.isNotEmpty),
      total: totalCount ?? this.totalCount,
    );

    return RefreshState<T>(
      status: combinedData.isEmpty ? PageStatus.empty : PageStatus.success,
      data: combinedData,
      hasMore: newPageInfo.hasMore,
      isLoadingMore: false,
      currentPage: newPageInfo.page,
      totalCount: newPageInfo.total,
      pageInfo: newPageInfo,
      isRefreshing: false,
    );
  }

  /// 重置状态
  @override
  RefreshState<T> reset() {
    return RefreshState<T>();
  }

  /// 更新页面信息
  RefreshState<T> updatePageInfo(PageInfo newPageInfo) {
    return RefreshState<T>(
      status: status,
      data: data,
      errorMessage: errorMessage,
      exception: exception,
      hasMore: newPageInfo.hasMore,
      isLoadingMore: isLoadingMore,
      currentPage: newPageInfo.page,
      totalCount: newPageInfo.total,
      pageInfo: newPageInfo,
      isRefreshing: isRefreshing,
    );
  }

  @override
  String toString() {
    return 'RefreshState(status: $status, itemCount: $itemCount, isRefreshing: $isRefreshing, pageInfo: $pageInfo)';
  }
}

/// 刷新分页通知器基类
abstract class RefreshNotifier<T> extends StateNotifier<RefreshState<T>> {
  RefreshNotifier({PageInfo? initialPageInfo})
      : super(RefreshState<T>(pageInfo: initialPageInfo ?? const PageInfo()));

  /// 设置加载状态
  void setLoading() {
    if (mounted) {
      state = state.loading();
    }
  }

  /// 设置刷新状态
  void setRefreshing() {
    if (mounted) {
      state = state.refreshing();
    }
  }

  /// 设置首次数据
  void setInitialData(List<T> data, PageInfo pageInfo) {
    if (mounted) {
      state = state.setInitialData(data, pageInfo);
    }
  }

  /// 设置空数据状态
  void setEmpty() {
    if (mounted) {
      state = state.empty();
    }
  }

  /// 设置错误状态
  void setError(String message, [Exception? exception]) {
    if (mounted) {
      state = state.error(message, exception);
    }
  }

  /// 设置加载更多状态
  void setLoadingMore() {
    if (mounted) {
      state = state.loadingMore();
    }
  }

  /// 添加更多数据
  void appendData(List<T> newData, PageInfo pageInfo) {
    if (mounted) {
      state = state.appendData(
        newData,
        totalCount: pageInfo.total,
        hasMore: pageInfo.hasMore,
      );
    }
  }

  /// 重置列表
  void reset() {
    if (mounted) {
      state = state.reset();
    }
  }

  /// 刷新数据
  Future<void> refresh() async {
    try {
      setRefreshing();
      final result = await loadFirstPage();
      if (result.$1.isEmpty) {
        setEmpty();
      } else {
        setInitialData(result.$1, result.$2);
      }
    } catch (e) {
      setError(e.toString(), e is Exception ? e : Exception(e.toString()));
    }
  }

  /// 加载更多数据
  Future<void> loadMore() async {
    if (state.isLoadingMore || !state.hasMore || state.isRefreshing) return;

    try {
      setLoadingMore();
      final result = await loadNextPage(state.pageInfo.nextPage);
      appendData(result.$1, result.$2);
    } catch (e) {
      setError(e.toString(), e is Exception ? e : Exception(e.toString()));
    }
  }

  /// 初始化加载数据
  Future<void> initialize() async {
    try {
      setLoading();
      final result = await loadFirstPage();
      if (result.$1.isEmpty) {
        setEmpty();
      } else {
        setInitialData(result.$1, result.$2);
      }
    } catch (e) {
      setError(e.toString(), e is Exception ? e : Exception(e.toString()));
    }
  }

  /// 加载第一页数据 - 子类实现
  /// 返回 (数据列表, 页面信息)
  Future<(List<T>, PageInfo)> loadFirstPage();

  /// 加载下一页数据 - 子类实现
  /// 返回 (数据列表, 页面信息)
  Future<(List<T>, PageInfo)> loadNextPage(int page);
}

/// 简化的分页参数类
class PageParams {
  final int page;
  final int size;
  final Map<String, dynamic>? filters;
  final String? sortBy;
  final String? sortOrder;

  const PageParams({
    this.page = 1,
    this.size = 20,
    this.filters,
    this.sortBy,
    this.sortOrder,
  });

  /// 转换为查询参数
  Map<String, dynamic> toParams() {
    final params = <String, dynamic>{
      'page': page,
      'size': size,
    };

    if (filters != null) {
      params.addAll(filters!);
    }

    if (sortBy != null) {
      params['sortBy'] = sortBy;
    }

    if (sortOrder != null) {
      params['sortOrder'] = sortOrder;
    }

    return params;
  }

  PageParams copyWith({
    int? page,
    int? size,
    Map<String, dynamic>? filters,
    String? sortBy,
    String? sortOrder,
  }) {
    return PageParams(
      page: page ?? this.page,
      size: size ?? this.size,
      filters: filters ?? this.filters,
      sortBy: sortBy ?? this.sortBy,
      sortOrder: sortOrder ?? this.sortOrder,
    );
  }
}
